﻿namespace LaoLuo
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// Provides a set of static methods for use with "flags" enums
    /// </summary>
    public static class FlagHelper
    {
        /// <summary>
        /// Returns all the bits used in any flag values
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns>A flag value with all the bits set</returns>
        /// <exception cref="TypeArgumentException"></exception>
        public static T GetAllBits<T>()
            where T : struct, IComparable, IFormattable, IConvertible
        {
            ThrowHelper.ThrowIfNotFlags<T>();

            return EnumInternals<T>.UsedBits;
        }

        /// <summary>
        /// 如果<paramref name="value"/>在类型为<paramref name="T"/>的标志位中定义, 则返回值, 否则返回标志位全开的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        /// <exception cref="TypeArgumentException"></exception>
        public static T GetAllBitsIfNoValue<T>(object value)
            where T : struct, IComparable, IFormattable, IConvertible
        {
            ThrowHelper.ThrowIfNotFlags<T>();

            return EnumHelper.TryParse<T>(value) ?? GetAllBits<T>();
        }
    }
}
